package com.bjpowernode.handler;

import cn.hutool.json.JSONUtil;
import com.bjpowernode.result.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.xml.transform.Result;
import java.io.IOException;

/**
 * 这个handler是当没有权限访问时，跳转执行这个handler
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //返回json，告诉前端，权限不足
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        R result = R.fail(401,"没有访问权限");
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
